"""Helper functions"""

import time
from routes import url_for
from webhelpers.html.tags import *

SECONDS_15_MINUTES = 60 * 15
SECONDS_ONE_HOUR = 60 * 60
SECONDS_ONE_DAY = SECONDS_ONE_HOUR * 24
SECONDS_ONE_WEEK = SECONDS_ONE_DAY * 7

def decode_uri(URI):
    """Decode JavaScript encodeURIComponent"""

    return URI.replace("&amp;", "&")


def to_unix_date(str_date):
    """ is able to convert DD.MM.YYYY and YYYY-MM-DD HH:MM:SS to sec-since-epoche """

    try:
        if "-" in str_date:
            ts = long(time.mktime(time.strptime(str_date, "%Y-%m-%d %H:%M:%S")))
        else:
            ts = long(time.mktime(time.strptime(str_date, "%d.%m.%Y")))
    except ValueError:
        ts = None

    return ts


def metrics_pick_first(l):
    l = [el for el in l if el is not None]
    if l:
        return l[0]
    else:
        return "n/a"

def metrics_average(l):
    l = [el for el in l if el != "n/a"]
    if l:
        l = [el for el in l if el is not None]
        if not l:
            return None
        return sum(l) / len(l)
    else:
        return "n/a"

def metrics_minimum(l):
    l = [el for el in l if el != "n/a"]
    if l:
        l = [el for el in l if el is not None]
        if not l:
            return None
        return min(l)
    else:
        return "n/a"

def metrics_maximum(l):
    l = [el for el in l if el != "n/a"]
    if l:
        l = [el for el in l if el is not None]
        if not l:
            return None
        return max(l)
    else:
        return "n/a"

def metrics_date_average(l):
    if l:
        l = [to_unix_date(ts) for ts in l if ts is not None]
        if not l:
            return None
        ts = sum(l) / len(l)
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))

def metrics_sum(l):
    l = [el for el in l if el != "n/a"]
    if l:
        l = [el for el in l if el is not None]
        if not l:
            return None
        return sum(l)
    else:
        return "n/a"

def norm_mime_type(mime_type):
    if not mime_type:
        return "other"

    if ";" in mime_type:
        mime_type = mime_type[:mime_type.index(";")]

    if "javascript" in mime_type:
        return "javascript"

    return mime_type

def shorten_url(url):
    if "?" in url:
        url = url[:url.index("?")]
    elif "#" in url:
        url = url[:url.index("#")]

    if len(url) > 64:
        url = url[:30] + "..." + url[30:]

    return url


